package com.demo.service.impl;


import com.demo.entity.Channel;
import com.demo.entity.Product;
import com.demo.entity.ProductRecord;
import com.demo.entity.User;
import com.demo.repository.ChannelRepo;
import com.demo.repository.ProductRecordRepo;
import com.demo.repository.ProductRepo;
import com.demo.repository.UserRepo;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by john on 2017/6/21.
 */
@Service
public class RecordServiceImpl {

    @Autowired
    private ProductRecordRepo productrecordrepo;

    @Autowired
    private UserRepo userRepo;

    @Autowired
    private ProductRecordRepo productRecordRepo;

    @Autowired
    private ProductRepo productRepo ;

    @Autowired
    private ChannelRepo channelRepo;

    @Transactional
    public ProductRecord save(String customer_name,String customer_phone,int product_id,int user_id) {


        Product product = productRepo.findOne(product_id);
        User user = userRepo.findOne(user_id);


        Channel channel = channelRepo.findOne(user.getChannelId());




        ProductRecord productRecord=new ProductRecord();
        productRecord.setUserId(user_id);
        productRecord.setProductId(product_id);
        productRecord.setCustomerName(customer_name);
        productRecord.setCustomerPhone(customer_phone);
        productRecord.setIsConfirm("0");
        productRecord.setMoney(product.getMoney());
        productRecord.setChannelId(channel.getId());
        productRecord.setAreaName(channel.getAreaName());
        productRecord.setCreateTime(new Date());
        productRecord.setChannelname(channel.getName());
        productRecord.setProductname(product.getName());
        productRecord.setUsername(user.getName());
        //List<ProductRecord> records= new ArrayList<ProductRecord>();

        productRecordRepo.save(productRecord);
        //records.add(productRecord);
        System.out.println(productRecord.getId()+"写入成功！");
        return productRecord;



    }

    public Integer getRank(Integer userId){
        List<Object[] > rows=productRecordRepo.findRankByAmount(userId);
        if (rows.size()>0) {
            Object[] row = rows.get(0);


            Double d = (Double) row[0];
            return d.intValue();
        }else{
            return null;
        }
    }



}
